package cn.seaboot.flake.where;

import cn.seaboot.flake.core.PreparedSql;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库 where 查询子句构建工具
 */
public class WhereClause {

    /**
     * 构建 where 子句
     *
     * @param conditions 查询条件
     * @return 查询条件
     */
    public static PreparedSql parse(List<WhereCondition> conditions) {
        StringBuilder sql = new StringBuilder().append("WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        for (WhereCondition condition : conditions) {
            sql.append(" AND ").append(condition.getTableName()).append(".").append(condition.getColumnName());
            getLogic(condition, sql, params);
        }
        return new PreparedSql(sql.toString(), params.toArray());
    }

    /**
     * 分析各种逻辑关系
     *
     * @param condition 查询条件
     * @param sb        查询语句
     * @param params    查询参数
     */
    public static void getLogic(WhereCondition condition, StringBuilder sb, List<Object> params) {
        Logical logical = condition.getLogical();
        if (logical == Logical.EQ) {
            sb.append(" = ?");
            params.add(condition.getValue());
        } else if (logical == Logical.GT) {
            sb.append(" > ?");
            params.add(condition.getValue());
        } else if (logical == Logical.LT) {
            sb.append(" < ?");
            params.add(condition.getValue());
        } else if (logical == Logical.LE) {
            sb.append(" <= ?");
            params.add(condition.getValue());
        } else if (logical == Logical.GE) {
            sb.append(" >= ?");
            params.add(condition.getValue());
        } else if (logical == Logical.LIKE) {
            sb.append(" LIKE ?");
            params.add("%" + condition.getValue() + "%");
        } else if (logical == Logical.BETWEEN) {
            sb.append(" BETWEEN ? AND ?");
            String[] arr = condition.getValue().split("[-~]");
            params.add(arr[0].trim());
            params.add(arr[1].trim());
        } else {
            throw new IllegalArgumentException("unknown logical " + logical);
        }
    }
}
